package com.bfd;

import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Properties;

/**
 * @author:yong.li
 * @date:2019/11/1 15:04
 */
public class ConsumerSample {
    public static void main(String[] args){
        String topic = "test-topic";
        Properties props = new Properties();
        props.put("bootstrap.servers","localhost:9092");
        props.put("group.id","testGroup1");
        //enable.auto.commit:kafka的offset是否自动提交
        props.put("enable.auto.commit","true");
        //auto.commit.interval.设置自动提交offset到zk的时间间隔，时间单位是毫秒
        props.put("auto.commit.interval.ms","1000");
        props.put("key.deserializer","org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer","org.apache.kafka.common.serialization.StringDeserializer");

        Consumer<String,String> consumer = new KafkaConsumer<String, String>(props);
        //subscribe,消费者订阅topic
        consumer.subscribe(Arrays.asList(topic));
        while (true){
            //poll方法来轮询kafka集群消息，一直等到kafka集群中没有消息，或达到超时时间，100毫秒。
            ConsumerRecords<String,String> records = consumer.poll(100);
            for (ConsumerRecord<String ,String> record : records){
                System.out.printf("partition = %d,offset = %d,key = %s,value = %s%n",record.partition(),record.offset(),record.key(),record.value());
            }
        }
    }
}
